package com.cheung.leetcode.tree;

import lyroot.entity.TreeNode;
import org.junit.jupiter.api.Test;

import java.util.*;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.tree
 * @Author :  cheungming
 * @CreateTime : 2024-05-18 08:42:34
 * @Description : 二叉树的右视图:遍历每一层，取每层最后一个元素即可
 * @Version : 1.0
 */
public class Code199Test {

    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                if (i == size - 1) {
                    res.add(node.val);
                }
            }
        }

        return res;
    }

    @Test
    public void test1() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(4);
        assert Objects.equals(rightSideView(root), Arrays.asList(1, 3, 4));
    }

    @Test
    public void test2() {
        TreeNode root = new TreeNode(1);
        root.right = new TreeNode(3);
        assert Objects.equals(rightSideView(root), Arrays.asList(1, 3));
    }

    @Test
    public void test3() {
        assert Objects.equals(rightSideView(null), List.of());
    }

    @Test
    public void test4() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        assert Objects.equals(rightSideView(root), Arrays.asList(1, 3, 4));
    }
}
